﻿using RXY_Mall.Core;
using System.Xml;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;

namespace RXY_Mall.Core.Sms
{
    /// <summary>
    /// 短信服务
    /// </summary>
    public class SMSHelper
    {
        #region 钱包SMS
        
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool SendSMS(string mobile, SMSType smsType, string code, out string error)
        {
            error = "";

            string appKey = AppConfig.KECSmsAppKey;
            string appSecret = AppConfig.KECSmsAppSecret;
            string product = AppConfig.KECSmsProductName;
            string smsFreeSignName = AppConfig.KECSmsFreeSignName;
            string url = AppConfig.KECSmsUrl;

            LogHelper.WriteLog(url);
            ITopClient client = new DefaultTopClient(url, appKey, appSecret);
            AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
            req.Extend = "";
            req.SmsType = "normal";
            req.SmsFreeSignName = smsFreeSignName;
            req.SmsParam = "{\"code\":\"" + code + "\",\"product\":\"" + product + "\"}";
            req.RecNum = mobile;
            string smsTemplateCode = "";
            switch (smsType)
            {
                case SMSType.Register:
                    smsTemplateCode = "SMS_62155242";
                    break;
                case SMSType.ForgetLoginPassword:
                    smsTemplateCode = "SMS_62155246";
                    break;
                case SMSType.ForgetPayPassword:

                    smsTemplateCode = "SMS_62155246";
                    break;
                default:
                    smsTemplateCode = "SMS_62155246";
                    break;
            }

            if (string.IsNullOrEmpty(smsTemplateCode))
            {
                error = "没有要发送的模板";
                return false;
            }

            req.SmsTemplateCode = smsTemplateCode;
            AlibabaAliqinFcSmsNumSendResponse rsp = client.Execute(req);
            var res = rsp.Body;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(res);
            XmlNode xn = doc.SelectSingleNode("/alibaba_aliqin_fc_sms_num_send_response/result/success");
            if (xn != null && xn.InnerText.Equals("true"))
            {
                return true;
            }

            XmlNode xnerror = doc.SelectSingleNode("/error_response/sub_msg");

            error = xnerror.InnerText;
            return false;
        }
        #endregion

    }
}
